<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :destroyOnClose="true"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :label-col="labelCol" :wrapper-col="wrapperCol"  :model="model" >

      </a-form-model>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="适应症" key="1" :forceRender="true">
          <j-vxe-table
            ref="editableTable1"
            toolbar
            row-selection
            keep-source
            :height="300"
            :loading="table1.loading"
            :dataSource="table1.dataSource"
            :columns="table1.columns"
            style="margin-top: 8px;"/>

        </a-tab-pane>

        <a-tab-pane tab="适用频次" key="2" :forceRender="true">
          <j-vxe-table
            ref="editableTable2"
            toolbar

            row-selection
            keep-source
            :height="300"
            :loading="table2.loading"
            :dataSource="table2.dataSource"
            :columns="table2.columns"
            style="margin-top: 8px;"/>
        </a-tab-pane>

        <a-tab-pane tab="用药途径" key="3" :forceRender="true">
          <j-vxe-table
            ref="editableTable3"
            toolbar

            row-selection
            keep-source
            :height="300"
            :loading="table3.loading"
            :dataSource="table3.dataSource"
            :columns="table3.columns"
            style="margin-top: 8px;"/>
        </a-tab-pane>

        <a-tab-pane tab="适用年龄" key="4" :forceRender="true">
          <j-vxe-table
            ref="editableTable4"
            toolbar

            row-selection
            keep-source
            :height="300"
            :loading="table4.loading"
            :dataSource="table4.dataSource"
            :columns="table4.columns"
            style="margin-top: 8px;"/>
        </a-tab-pane>

        <a-tab-pane tab="性别禁忌" key="5" :forceRender="true">
          <j-vxe-table
            ref="editableTable5"
            toolbar

            row-selection
            keep-source
            :height="300"
            :loading="table5.loading"
            :dataSource="table5.dataSource"
            :columns="table5.columns"
            style="margin-top: 8px;"/>
        </a-tab-pane>

        <a-tab-pane tab="联用禁忌" key="6" :forceRender="true">
          <j-vxe-table
            ref="editableTable6"
            toolbar

            row-selection
            keep-source
            :height="300"
            :loading="table6.loading"
            :dataSource="table6.dataSource"
            :columns="table6.columns"
            style="margin-top: 8px;"/>
        </a-tab-pane>

        <a-tab-pane tab="剂量" key="7" :forceRender="true">
          <j-vxe-table
            ref="editableTable7"
            toolbar

            row-selection
            keep-source
            :height="300"
            :loading="table7.loading"
            :dataSource="table7.dataSource"
            :columns="table7.columns"
            style="margin-top: 8px;"/>
        </a-tab-pane>

      </a-tabs>

    </a-spin>
  </a-modal>
</template>

<script>

  import JEditableTable from '@/components/jeecg/JEditableTable'
  import { VALIDATE_FAILED, getRefPromise, validateFormModelAndTables } from '@/components/jeecg/JVxeTable/utils/vxeUtils'
  import { httpAction, getAction } from '@/api/manage'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import JDate from '@/components/jeecg/JDate'

  export default {
    name: 'SubList',
    components: {
      JDate, JEditableTable
    },
    data() {
      return {
        title: '操作',
        visible: false,
        confirmLoading: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 - 6 }
        },
        activeKey: '1',
        // 适应症
        table1: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 1,
            },
            {
              title: '规则类型',
              key: 'condition',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '禁用', value: '1' },
                { title: '适用', value: '0' },
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '适应症',
              key: 'value',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        // 频次
        table2: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 3,
            },
            {
              title: '频次',
              key: 'value',
              width: '24%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '一天1次', value: '一天1次' },
                { title: '一天2次', value: '一天2次' },
              ],
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        //用药途径
        table3: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 4,
            },
            {
              title: '规则类型',
              key: 'condition',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '禁用', value: '1' },
                { title: '适用', value: '0' },
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '用药途径',
              key: 'value',
              width: '24%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '口服', value: '口服' },
                { title: '外敷', value: '外敷' },
              ],
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        //适用年龄
        table4: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 6,
            },
            {
              title: '规则类型',
              key: 'condition',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '禁用', value: '1' },
                { title: '适用', value: '0' },
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '适用年龄',
              key: 'value',
              width: '24%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '口服', value: '口服' },
                { title: '外敷', value: '外敷' },
              ],
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        //性别禁忌
        table5: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 7,
            },
            {
              title: '性别',
              key: 'value',
              width: '24%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '女', value: '0' },
                { title: '男', value: '1' },
              ],
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        //联用禁忌
        table6: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 9,
            },
            {
              title: '规则类型',
              key: 'condition',
              width: '18%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '禁忌药品编号',
              key: 'value',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        //剂量
        table7: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'type',
              key: 'type',
              width: '18%',
              type: JVXETypes.hidden,
              defaultValue: 20,
            },
            {
              title: '规则类型',
              key: 'subtype',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '单次', value: '0' },
                { title: '单日', value: '1' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '常量',
              key: 'constant',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            },
            {
              title: '极量',
              key: 'max',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            },
            {
              title: '动作',
              key: 'act',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: '签字确认', value: '0' },
                { title: '强制拦截', value: '1' },
                { title: '提醒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '单位',
              key: 'unit',
              width: '18%',
              type: JVXETypes.select,
              options: [ // 下拉选项
                { title: 'mg', value: '0' },
                { title: 'g', value: '1' },
                { title: '粒', value: '3' }
              ],
              defaultValue: '',
              placeholder: '请选择${title}'
            },
            {
              title: '拦截消息',
              key: 'msg',
              width: '24%',
              type: JVXETypes.input,
              defaultValue: '',
              placeholder: '请输入${title}'
            }
          ]
        },
        url: {
          add: '/rule/add',
          edit: '/rule/edits',
          list1: '/rule/getRulesList1',
          list2: '/rule/getRulesList3',
          list3: '/rule/getRulesList4',
          list4: '/rule/getRulesList6',
          list5: '/rule/getRulesList7',
          list6: '/rule/getRulesList9',
          list7: '/rule/getDosageRulesList',
        }
      }
    },
    created() {
    },
    methods: {

      // 获取所有的editableTable实例
      getAllTable() {
        return Promise.all([
          getRefPromise(this, 'editableTable1'),
          getRefPromise(this, 'editableTable2'),
          getRefPromise(this, 'editableTable3'),
          getRefPromise(this, 'editableTable4'),
          getRefPromise(this, 'editableTable5'),
          getRefPromise(this, 'editableTable6'),
          getRefPromise(this, 'editableTable7'),
        ])
      },

      add() {
        // 默认新增一条数据
        this.getAllTable().then(editableTables => {
          editableTables[0].add()
          editableTables[1].add()
        })
        this.edit({})
      },
      edit(record) {
        this.visible = true
        this.activeKey = '1'
        this.model = Object.assign({}, record)
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestTableData(this.url.list1, params, this.table1)
          this.requestTableData(this.url.list2, params, this.table2)
          this.requestTableData(this.url.list3, params, this.table3)
          this.requestTableData(this.url.list4, params, this.table4)
          this.requestTableData(this.url.list5, params, this.table5)
          this.requestTableData(this.url.list6, params, this.table6)
          this.requestTableData(this.url.list7, params, this.table7)
        }

      },
      close() {
        this.visible = false
        this.getAllTable().then(editableTables => {
          this.table1.dataSource=[];
          this.table2.dataSource=[];
        })
        this.$emit('close')
      },
      /** 查询某个tab的数据 */
      requestTableData(url, params, tab) {
        tab.loading = true
        getAction(url, params).then(res => {
          tab.dataSource = res.result || []
        }).finally(() => {
          tab.loading = false
        })
      },
      handleOk() {
        this.validateFields()
      },
      handleCancel() {
        this.close()
      },
      /** ATab 选项卡切换事件 */
      handleChangeTabs(key) {
        getRefPromise(this, `editableTable${key}`).then(editableTable => {
          editableTable.resetScrollTop()
        })
      },

      /** 触发表单验证 */
      validateFields() {
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormModelAndTables(this.$refs.form,this.model, tables)
        }).then(allValues => {
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.requestAddOrEdit(formData)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : (e.index + 1).toString()
          } else {
            console.error(e)
          }
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let orderMain = Object.assign(this.model, allValues.formValue)
        let ruleList = []
        let ruleDosageList = []
        ruleList = ruleList.concat(allValues.tablesValue[0].tableData)
        ruleList = ruleList.concat(allValues.tablesValue[1].tableData)
        ruleList = ruleList.concat(allValues.tablesValue[2].tableData)
        ruleList = ruleList.concat(allValues.tablesValue[3].tableData)
        ruleList = ruleList.concat(allValues.tablesValue[4].tableData)
        ruleList = ruleList.concat(allValues.tablesValue[5].tableData)
        ruleDosageList = allValues.tablesValue[6].tableData
        return {
          ...orderMain, // 展开
          ruleList: ruleList,
          ruleDosageList: ruleDosageList
        }
      },
      /** 发起新增或修改的请求 */
      requestAddOrEdit(formData) {
        let url = this.url.edit, method = 'post'
        console.log(formData)
        this.confirmLoading = true
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      }

    }
  }
</script>

<style scoped>
</style>